/**
* 系统管理  权限管理
*/
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>下发工单</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form class="user-search" label-position="top" :model="formInline" :rules="rules" ref="formInline">
      <el-form-item label="接收用户" style="width: 30%" prop="userId">
        <el-input v-model="userName" auto-complete="off" placeholder="请选择部门负责人" disabled>
          <el-button slot="append" @click="chooseUser" icon="el-icon-s-custom"></el-button>
        </el-input>
      </el-form-item>

      <el-form-item label="工单标题" style="width: 30%" prop="orderTitle">
        <el-input v-model="formInline.orderTitle"></el-input>
      </el-form-item>
      <el-form-item label="工单时间" style="width: 50%" prop="time">
        <el-date-picker
          v-model="formInline.time"
          type="datetimerange"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          align="right">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="工单内容" style="width: 100%" prop="orderContent">
        <editor id='tinymce' v-model='formInline.orderContent' :init='init'></editor>
      </el-form-item>
    </el-form>
    <!--上传-->
    <el-upload
      class="upload-demo user-search"
      ref="upload"
      :http-request="uploadFile"
      action="/officeSystem/file/uploadOrderFile"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :file-list="fileList"
      :auto-upload="false"
      :limit="5"
      :on-exceed="handleExceed"
      multiple
      style="width: 500px">
      <el-button
        style="margin-left: 10px;"
        size="small"
        type="success"
        @click="submitUpload('formInline')"
        :loading="loading">下发工单
      </el-button>
      <el-button slot="trigger" size="small" type="primary">添加附件</el-button>
      <div slot="tip" class="el-upload__tip"></div>
    </el-upload>

    <el-dialog
      width="50%"
      title="选择部门负责人"
      :visible.sync="innerVisible"
      append-to-body>
      <el-form :inline="true" :model="queryUserForm" class="user-search">
        <el-form-item label="搜索：">
          <el-input size="small" v-model="queryUserForm.userCodeOrName" placeholder="输入用户编码或名称" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" icon="el-icon-search" @click="searchUser">搜索</el-button>
        </el-form-item>
      </el-form>
      <el-table
        ref="singleTable"
        :data="userList"
        highlight-current-row
        @current-change="handleCurrentChange"
        style="width: 100%"
        height="200"
        size="mini">
        <el-table-column
          type="index"
          label="序号"
          width="100"
          align="center">
        </el-table-column>
        <el-table-column
          property="userCode"
          label="用户编码"
          align="center">
        </el-table-column>
        <el-table-column
          property="userName"
          label="姓名"
          align="center">
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <Pagination v-bind:child-msg="pageparmUser" @callFather="callFatherUser"></Pagination>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="innerVisible = false">取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitSelect">保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
    import Pagination from '../../components/Pagination';
    import {timestampToTime, timestampToDate} from "../../utils/util";
    import {Get, Post} from "../../api/axiosFun";

    import tinymce from 'tinymce/tinymce'
    import Editor from '@tinymce/tinymce-vue'
    import 'tinymce/themes/silver/theme'
    import 'tinymce/plugins/image'
    import 'tinymce/plugins/link'
    import 'tinymce/plugins/code'
    import 'tinymce/plugins/table'
    import 'tinymce/plugins/lists'
    import 'tinymce/plugins/contextmenu'
    import 'tinymce/plugins/wordcount'
    import 'tinymce/plugins/colorpicker'
    import 'tinymce/plugins/textcolor'

    export default {
        data() {
            return {
                init: {
                    // 引入汉化组件
                    language_url: '../../../static/tinymce/langs/zh_CN.js',
                    // 设定语言为中文
                    language: 'zh_CN',
                    // 加入主题
                    skin_url: '../../../static/tinymce/skins/ui/oxide',
                    height: 400,
                    menubar: 'file edit insert view format table',
                    plugins: 'advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount',
                    toolbar:
                        'bold italic underline strikethrough | fontsizeselect | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist | outdent indent blockquote | undo redo | link unlink image media code | removeformat',
                    branding: false,
                    //此处为图片上传处理函数，这个直接用了base64的图片形式上传图片，
                    //如需ajax上传可参考https://www.tiny.cloud/docs/configure/file-image-upload/#images_upload_handler
                    images_upload_handler: (blobInfo, success, failure) => {
                        let formdata = new FormData()
                        formdata.set('file', blobInfo.blob())
                        this.$axios.post('/officeSystem/file/upload', formdata)
                            .then(res => {
                                if(res.status == 200){
                                    console.log(res)
                                    success(res.data.data.fileUrl)
                                }else{
                                    failure(res.message)
                                }
                            })
                            .catch(res => {
                                failure(res.message)
                            })
                    }
                },

                loading: false,
                pickerOptions: {
                    disabledDate(time) {
                        let now = `${timestampToDate(new Date())}`
                        return time.getTime() < new Date(now).getTime();
                    },
                    shortcuts: [{
                        text: '最近一周',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() + 3600 * 1000 * 24 * 7);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '最近一个月',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() + 3600 * 1000 * 24 * 30);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '最近三个月',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() + 3600 * 1000 * 24 * 90);
                            picker.$emit('pick', [start, end]);
                        }
                    }]
                },
                userName: '',
                formInline: {
                    userId: '',
                    orderTitle: '',
                    orderContent: '',
                    time: []
                },
                // rules表单验证
                rules: {
                    userId: [
                        {required: true, message: '请选择下发用户', trigger: 'blur'}
                    ],
                    orderTitle: [
                        {required: true, message: '请输入工单标题', trigger: 'blur'}
                    ],
                    orderContent: [
                        {required: true, message: '请输入工单内容', trigger: 'blur'}
                    ],
                    time: [
                        {required: true, message: '请选择工单时间', trigger: 'blur'}
                    ],
                },

                fileList: [],
                uploadForm: new FormData(),

                innerVisible: false,
                userList: [],
                queryUserForm: {
                    pageIndex: 0,
                    pageSize: 10,
                    userCodeOrName: '', // 搜索用户
                },
                pageparmUser: {
                    currentPage: 1,
                    pageSize: 10,
                    total: 10
                }
            }
        },
        // 注册组件
        components: {
            Pagination,
            Editor
        },
        /**
         * 数据发生改变
         */

        watch: {},

        /**
         * 创建完毕
         */
        mounted() {
            tinymce.init({})
        },
        created() {

        },

        /**
         * 里面的方法只有被调用才会执行
         */

        methods: {
            uploadFile(file) {
                this.uploadForm.append('file', file.file);
            },
            submitUpload(editData) {
                this.loading = true;
                this.$refs[editData].validate((valid) => {
                    if (valid) {
                        this.$refs.upload.submit();
                        this.uploadForm.append('userId', this.formInline.userId);
                        this.uploadForm.append('startTime', this.formInline.time[0]);
                        this.uploadForm.append('endTime', this.formInline.time[1]);
                        this.uploadForm.append('orderTitle', this.formInline.orderTitle);
                        this.uploadForm.append('orderContent', this.formInline.orderContent);
                        let config = {
                            headers: {
                                'Content-Type': 'multipart/form-data'
                            }
                        }
                        this.$axios.post("/officeSystem/file/uploadOrderFile", this.uploadForm, config)
                            .then(res => {
                                this.loading = false;
                                this.uploadForm = new FormData();
                                if (res.data.status == 200) {
                                    this.$message.success(res.data.message);
                                    window.location.reload();
                                } else {
                                    this.$message.error(res.data.message);
                                }
                            }).catch(err => {
                            this.loading = false;
                            this.uploadForm = new FormData();
                            this.$message.error(err.data.message);
                        })
                    } else {
                        this.loading = false;
                        return false;
                    }
                })
            },
            handleRemove(file, fileList) {
                console.log(file, fileList);
            },
            handlePreview(file) {
                console.log(file);
            },
            handleExceed(file, fileList) {
                this.$message.warning("最多添加五个附件")
                // console.log(file, fileList);
            },

            // 获取用户列表
            searchUser() {
                Get("/officeSystem/user/selectByCondition", this.queryUserForm)
                    .then(result => {
                        if (result.status == 200) {
                            this.pageparmUser.total = result.data.totalCount;
                            this.userList = result.data.resultList
                        } else {
                            this.pageparmUser.total = result.data.totalCount;
                            this.userList = []
                        }
                    })
            },
            chooseUser() {
                this.searchUser()
                this.innerVisible = true
            },
            handleCurrentChange(val) {
                this.selectUser = val;
            },
            submitSelect() {
                this.userName = this.selectUser.userName
                this.formInline.userId = this.selectUser.id
                this.innerVisible = false
            },
            callFatherUser(parm) {
                this.queryUserForm.pageIndex = parm.currentPage - 1
                this.queryUserForm.pageSize = parm.pageSize
                this.searchUser(this.queryUserForm)
            },
        }
    }
</script>

<style scoped>
  .user-search {
    margin-top: 20px;
  }

  .userRole {
    width: 100%;
  }

  .quillWrapper {
    width: 100%;
  }
</style>

